const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
const cors = require("cors");
const port = 3000;

// 设置跨域
const corsOptions = {
  origin: "*",
  credentials: true,
};

// 全局设置跨域
app.use(cors(corsOptions));

// 配置body-parser
app.use(bodyParser.json());

app.options("/chat", (req, res) => {
  res.setHeader("Access-Control-Allow-Methods", "POST");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");
  res.status(200).end();
});

const setHeader = function (req, res, next) {
  // 设置响应头为SSE格式
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  next();
};

const options = {
  method: "POST",
  hostname: "dashscope.aliyuncs.com",
  path: "/api/v1/services/aigc/text-generation/generation",
  headers: {
    "Content-Type": "application/json",
    Accept: "text/event-stream",
    Authorization: "Bearer sk-fw9kVQOJY4",
    "X-DashScope-SSE": "enable",
  },
};

app.post("/chat", setHeader, (req, res) => {
  const reqStream = https.request(options, (resStream) => {
    resStream.on("data", (chunk) => {
      res.write(chunk.toString());
    });
    resStream.on("end", () => {
      res.end();
    });
  });
  reqStream.on("error", (error) => {
    console.error(error);
  });
  // 发送请求
  reqStream.write(
    JSON.stringify({
      input: {
        messages: req.body.messages,
      },
      model: "qwen-turbo",
    })
  );
  reqStream.end();
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
